const util = require('util');
const Excel = require('exceljs');

const d = {};
d.obj2excel = async function(template_name, obj, template_header_row_index) {
  const workbook = new Excel.Workbook();
  console.log("reading excel...");
  const template_file_path = process.cwd() + "/resources/templates/" + template_name + "_template.xlsx";
  await workbook.xlsx.readFile(template_file_path);
  console.log("read excel, column count: " + workbook.worksheets[0].actualColumnCount);
  const template_headers = workbook.worksheets[0].getRow(template_header_row_index).values;
  let columns = [];
  template_headers.forEach((item, index) => {
    columns.push({ header: item, key: item, width: 10 })
  });
  // JM: 这里有个tricky， 逻辑是暂存原template的首行，等设置完values后再替换回来。
  // 因为下面设置worksheet.columns会实际导致首行发生变化
  // Amazon是不允许修改template文件前三行的。我们需要设置worksheet的column，这样就能直接将对象设置到worksheet.row
  const origin_headers = workbook.worksheets[0].getRow(1).values; // 这里不论template_header_row_index是否第一行，都必须临时保存首行数据
  workbook.worksheets[0].columns = columns;
  if (util.isArray(obj)){
    for(const i of obj.keys()){
      workbook.worksheets[0].getRow(template_header_row_index+1+i).values = obj[i];
    }
  } else {
    workbook.worksheets[0].getRow(template_header_row_index+1).values = obj;
  }
  workbook.worksheets[0].getRow(1).values = origin_headers;
  return workbook.xlsx;
  // await workbook.xlsx.writeFile(".\\spec\\resources\\aaa_1111.xlsx");
  // return await workbook.xlsx.writeBuffer();
};


module.exports = d;